﻿using Microsoft.Practices.ServiceLocation;
using CommonServiceLocator.WindsorAdapter;
using Castle.Windsor;
using Castle.MicroKernel.Facilities.OnCreate;
using Castle.MicroKernel.Registration;
using Castle.Facilities.FactorySupport;
using MM.Bootstrapper.Configurators;
using uNhAddIns.Adapters;

namespace MM.Bootstrapper
{
    public class GeneralGuyWire : IGuyWire
    {
        private readonly IConfigurator[] configurators = new IConfigurator[] {
                                                                  new NHibernateConfigurator(),      
                                                                  new RepositoriesConfigurator(),
                                                                  new ControllerConfigurator(),
                                                                  new NHVConfigurator(),
                                                                  new ServiceConfigurator()

                                                        };

        private IWindsorContainer container;

        #region Miembros de IGuyWire

        public void Wire()
        {
            if (container != null)
                container.Dispose();

            container = new WindsorContainer();
            container.AddFacility<OnCreateFacility>();
            container.AddFacility<FactorySupportFacility>();

            ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(container));
            container.Register(Component.For<IServiceLocator>()
                                        .Instance(ServiceLocator.Current)
                              );

            
            foreach (IConfigurator configurator in configurators)
            {
                configurator.Configure(container);
            }
        }

        public void Dewire()
        {
            if (container != null)
                container.Dispose();
        }

        #endregion
    }
}
